package com.eightywork.life.activity;

import java.io.File;

import cn.jpush.android.api.JPushInterface;

import com.eightywork.life.R;
import com.eightywork.life.imageCache.ImageLoader;
import com.eightywork.life.model.Space;
import com.eightywork.life.service.CacheService;
import com.eightywork.life.service.CpService;
import com.eightywork.life.service.DataService;
import com.eightywork.life.util.FileUtil;
import com.eightywork.life.util.MyHttpException;
import com.eightywork.life.util.PhotoUtil;
import com.umeng.analytics.MobclickAgent;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class EditActivity extends BaseActivity implements OnClickListener {
	private ImageButton leftButton;
	private Button saveButton, modiAvatar;
	private EditText home, name, birthday, mobile, note, address;
	private CheckBox privacymarry, privacybirth, privacybirthcity, privacysex,
			privacymobile;
	private ViewGroup marry, sex, marryLayout, sexLayout, bitrthLayout,
			homeLayout, addressLayout, noteLayout;
	private ImageView avatar, verifyType;
	private Space space;
	private ImageLoader imageLoader;
	private AsyncTask<?, ?, ?> task, upload;
	private DatePickerDialog dialog;
	private File file;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_edit);
		initView();
		initData();
	}
	
	@Override
	public void onResume() {		
		super.onResume();
		JPushInterface.onResume(this);
	    MobclickAgent.onResume(this);
	}
	
	@Override
	public void onPause() {
	    super.onPause();
		JPushInterface.onPause(this);
	    MobclickAgent.onPause(this);
	}


	@Override
	public void onDestroy() {
		if (task != null) {
			task.cancel(true);
		}
		if (upload != null) {
			upload.cancel(true);
		}
		super.onDestroy();
	}

	public void initView() {
		leftButton = (ImageButton) findViewById(R.id.button_left);
		saveButton = (Button) findViewById(R.id.button_save);
		modiAvatar = (Button) findViewById(R.id.modi_avatar);
		avatar = (ImageView) findViewById(R.id.avatar);
		verifyType = (ImageView) findViewById(R.id.verify_type);
		home = (EditText) findViewById(R.id.home);
		birthday = (EditText) findViewById(R.id.birthday);
		name = (EditText) findViewById(R.id.name);
		mobile = (EditText) findViewById(R.id.mobile);
		note = (EditText) findViewById(R.id.note);
		address = (EditText) findViewById(R.id.address);
		marry = (ViewGroup) findViewById(R.id.marry);
		sex = (ViewGroup) findViewById(R.id.sex);
		bitrthLayout = (ViewGroup) findViewById(R.id.birthday_layout);
		homeLayout = (ViewGroup) findViewById(R.id.home_layout);
		sexLayout = (ViewGroup) findViewById(R.id.sex_layout);
		addressLayout = (ViewGroup) findViewById(R.id.address_layout);
		noteLayout = (ViewGroup) findViewById(R.id.note_layout);
		marryLayout = (ViewGroup) findViewById(R.id.marry_layout);
		privacymarry = (CheckBox) findViewById(R.id.privacymarry);
		privacybirth = (CheckBox) findViewById(R.id.privacybirth);
		privacybirthcity = (CheckBox) findViewById(R.id.privacybirthcity);
		privacysex = (CheckBox) findViewById(R.id.privacysex);
		privacymobile = (CheckBox) findViewById(R.id.privacymobile);
		leftButton.setOnClickListener(this);
		birthday.setOnClickListener(this);
		home.setOnClickListener(this);
		saveButton.setOnClickListener(this);
		modiAvatar.setOnClickListener(this);
	}

	public void initData() {
		imageLoader = new ImageLoader(context);
		space = CacheService.getSpace();
		initMarry();
		initSex();
		name.setText(space.getName());
		home.setText(space.getBirthcity());
		birthday.setText(space.getBirth());
		mobile.setText(space.getMobile());
		note.setText(space.getNote());
		address.setText(space.getVerify_address());
		if (space.getVerifyType() != null) {
			verifyType.setVisibility(View.VISIBLE);
			verifyType.setBackgroundResource(DataService.getVerifyTypeRes(space
					.getVerifyType()));
		}
	    if (space.getPrivacy() != null) {	
			privacymarry.setChecked(space.getPrivacy().get("marry")
					.getAsString().equals("0") ? true : false);
			privacybirth.setChecked(space.getPrivacy().get("birth")
					.getAsString().equals("0") ? true : false);
			privacybirthcity.setChecked(space.getPrivacy().get("birthcity")
					.getAsString().equals("0") ? true : false);
			privacysex.setChecked(space.getPrivacy().get("sex").getAsString()
					.equals("0") ? true : false);
			privacymobile.setChecked(space.getPrivacy().get("mobile")
					.getAsString().equals("0") ? true : false);
			imageLoader.DisplayImage(space.getAvatar(), avatar, 0, 0, 0);
		}
		if (space.getVerifyType().equals("4")) {
			bitrthLayout.setVisibility(View.GONE);
			homeLayout.setVisibility(View.GONE);
			sexLayout.setVisibility(View.GONE);
			marryLayout.setVisibility(View.GONE);
		} else {
			addressLayout.setVisibility(View.GONE);
		}
	}

	private void initMarry() {
		for (int i = 0; i < marry.getChildCount(); i++) {
			TextView view = (TextView) marry.getChildAt(i);
			if (view.getText().equals(
					DataService.getMarryMap().get(space.getMarry()))) {
				view.setTextColor(getResources().getColor(R.color.white));
				view.setBackgroundColor(getResources().getColor(R.color.green));
			} else {
				view.setTextColor(getResources().getColor(R.color.dark_gray));
				view.setBackgroundColor(getResources().getColor(
						R.color.font_light_gray));
			}
			view.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					selectView(marry, (TextView) arg0);
				}
			});
		}
	}

	private void initSex() {
		for (int i = 0; i < sex.getChildCount(); i++) {
			TextView view = (TextView) sex.getChildAt(i);
			if (view.getText().equals(
					DataService.getSexMap().get(space.getSex()))) {
				view.setTextColor(getResources().getColor(R.color.white));
				view.setBackgroundColor(getResources().getColor(R.color.green));
			} else {
				view.setTextColor(getResources().getColor(R.color.dark_gray));
				view.setBackgroundColor(getResources().getColor(
						R.color.font_light_gray));
			}
			view.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					selectView(sex, (TextView) arg0);
				}
			});
		}
	}

	private void selectView(ViewGroup group, TextView view) {
		for (int i = 0; i < group.getChildCount(); i++) {
			TextView textView = (TextView) group.getChildAt(i);
			textView.setTextColor(getResources().getColor(R.color.dark_gray));
			textView.setBackgroundColor(getResources().getColor(
					R.color.font_light_gray));
			textView.setSelected(false);
		}
		view.setTextColor(getResources().getColor(R.color.white));
		view.setBackgroundColor(getResources().getColor(R.color.green));
		view.setSelected(true);
	}

	private String getSelectView(ViewGroup group) {
		for (int i = 0; i < group.getChildCount(); i++) {
			TextView textView = (TextView) group.getChildAt(i);
			if (textView.isSelected()) {
				return (String) textView.getTag();
			}
		}
		return "0";
	}

	@Override
	public void onClick(View v) {
		if (leftButton == v) {
			finish();
		} else if (home == v) {
			showProvinceDialog();
		} else if (birthday == v) {
			showBirthdayDialog(birthday.getEditableText().toString());
		} else if (saveButton == v) {
			if (file != null) {
				upload();
			} else {
				save();
			}
		} else if (modiAvatar == v) {
			modiAvatar();
		}
	}

	private void modiAvatar() {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setItems(new String[] { "拍照", "选择图片" },
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case 0:
							PhotoUtil.takePhotoByCamera(context);
							break;
						case 1:
							PhotoUtil.choesePhoto(context);
							break;
						}
					}
				});
		builder.show();
	}

	@Override
	protected void onActivityResult(int requsetCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			switch (requsetCode) {
			case PhotoUtil.PHOTO_PICKED_WITH_DATA:
				File file = FileUtil.saveFile(data.getData(),
						PhotoUtil.getPackName(context), "temp", context);
				addPicView(Uri.fromFile(file));
				break;
			case PhotoUtil.CAMERA_WITH_DATA:
				addPicView(Uri.fromFile(PhotoUtil.getSaveFile(context)));
				break;
			}
		}
		super.onActivityResult(requsetCode, resultCode, data);
	}

	private void addPicView(Uri uri) {
		Bitmap bitmap = PhotoUtil.loadPhoto(uri, context, 96, 0);
		file = PhotoUtil.saveBitmap(bitmap, PhotoUtil.getPhotoPath(context)
				+ "/" + System.currentTimeMillis() + ".png");
		avatar.setImageBitmap(bitmap);
	}

	private void save() {
		String name_ = name.getEditableText().toString();
		String birth_ = birthday.getEditableText().toString();
		String marry_ = getSelectView(marry);
		String sex_ = getSelectView(sex);
		String birthcity_ = home.getEditableText().toString();
		String mobile_ = mobile.getEditableText().toString();
		String note_ = note.getEditableText().toString();
		String address_ = address.getEditableText().toString();
		String friendbirth_ = privacybirth.isChecked() ? "0" : "3";
		String friendmarry_ = privacymarry.isChecked() ? "0" : "3";
		String friendbirthcity_ = privacybirthcity.isChecked() ? "0" : "3";
		String friendsex_ = privacysex.isChecked() ? "0" : "3";
		String friendmobile_ = privacymobile.isChecked() ? "0" : "3";
		if (name_.equals("")) {
			name.setError(Html.fromHtml("<font color=red>请填写昵称</font>"));
			return;
		}
		String birthyear_ = "";
		String birthmonth_ = "";
		String birthday_ = "";
		if (!birth_.equals("")) {
			birthyear_ = birth_.split("-")[0];
			birthmonth_ = birth_.split("-")[1];
			birthday_ = birth_.split("-")[2];
		}
		task = new SaveTask().execute(name_, birthyear_, birthmonth_,
				birthday_, marry_, sex_, "", birthcity_, "", friendbirth_,
				friendmarry_, friendbirthcity_, "", friendsex_, friendmobile_,
				mobile_, note_, address_);
	}

	private void upload() {
		upload = new UploadTask().execute();
	}

	class SaveTask extends AsyncTask<String, Void, String> {
		@Override
		protected void onPreExecute() {
			showProgressDialog("正在保存信息...");
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			try {
				CpService.profileBase(params[0], params[1], params[2],
						params[3], params[4], params[5], params[6], params[7],
						params[8], params[9], params[10], params[11],
						params[12], params[13], params[14], params[15],
						params[16], params[17]);
				CacheService.saveProfile(CpService.profile());
			} catch (MyHttpException e) {
				return e.getErrorMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			hideProgressDialog();
			if (result == null) {
				finish();
			} else {
				showMessage(result);
			}
			super.onPostExecute(result);
		}
	}

	class UploadTask extends AsyncTask<String, Void, String> {
		@Override
		protected void onPreExecute() {
			showProgressDialog("正在上传图片...");
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			try {
				CpService.avatar(file);
			} catch (MyHttpException e) {
				return e.getErrorMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			hideProgressDialog();
			if (result == null) {
				save();
				finish();
			} else {
				showMessage(result);
			}
			super.onPostExecute(result);
		}
	}

	private void showBirthdayDialog(String date) {
		String time[] = "1990-1-1".split("-");
		if (!date.equals("")) {
			time = date.split("-");
		}
		dialog = new DatePickerDialog(context, new OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
				birthday.setText(arg0.getYear() + "-" + (arg0.getMonth() + 1)
						+ "-" + arg0.getDayOfMonth());
				birthday.setError(null);
			}
		}, Integer.valueOf(time[0]), Integer.valueOf(time[1]) - 1, Integer
				.valueOf(time[2]));
		dialog.setTitle("选择生日");
		dialog.show();
	}

	private void showProvinceDialog() {
		final String[] array = DataService.getProvince();
		AlertDialog.Builder bulder = new AlertDialog.Builder(context);
		bulder.setTitle("选择省份");
		ListView listView = new ListView(context);
		bulder.setView(listView);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,
				android.R.layout.simple_list_item_single_choice, array);
		listView.setAdapter(adapter);
		listView.setBackgroundColor(Color.WHITE);
		final AlertDialog dialog = bulder.create();
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int arg2,
					long arg3) {
				showCityDialog(array[arg2]);
				dialog.dismiss();
			}
		});
		dialog.show();
	}

	private void showCityDialog(final String province) {
		final String[] array = DataService.getCity(province);
		AlertDialog.Builder bulder = new AlertDialog.Builder(context);
		bulder.setTitle("选择城市");
		ListView listView = new ListView(context);
		bulder.setView(listView);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,
				android.R.layout.simple_list_item_single_choice, array);
		listView.setAdapter(adapter);
		listView.setBackgroundColor(Color.WHITE);
		final AlertDialog dialog = bulder.create();
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int arg2,
					long arg3) {
				home.setText(array[arg2]);
				home.setError(null);
				dialog.dismiss();
			}
		});
		dialog.show();
	}
}
